/**
 *  Stack - Array Implementation
 *
 */

public class StackArray<T> {
    
    private T[] arr;

    private int total;

    public StackArray() {
        arr = (T[]) new Object[1];
    }

    public void push(T item) {
        if (arr.length == total) {
            resize(total * 2);
        }

        arr[total++] = item;
    }

    public T pop() {
        if (total == 0) {
            return null;
        }

        T item = arr[--total];
        arr[total] = null;

        if (total == arr.length / 4) {
            resize(total / 2);
        }

        return item;
    }

    public int size() {
        return total;
    }

    public Boolean isEmpty() {
        return total == 0;
    }

    public T peek() {
        if (total == 0) {
            return null;
        }
        return arr[total - 1];
    }

    private void resize(int capacity) {
        T[] tmp = (T[]) new Object[capacity];
        System.arraycopy(arr, 0, tmp, 0, total);
        arr = tmp;
    }

    @Override
    public String toString() {
        return java.util.Arrays.toString(arr);
    }

}
